﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DrawForm.aspx.cs" Inherits="Cms.Web.CmsSystem.SysAdmin.FormSetting.DrawForm" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>绘制</title>
    <script src="/Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
    <script src="/Scripts/easyui/jquery.easyui.min.js" type="text/javascript"></script>
    <script src="/Scripts/easyui/src/jquery.propertygrid.js" type="text/javascript"></script>
    <link href="/App_Themes/Default/easyui/easyui.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/JQueryPlugins/jquery.dragToSelect.js" type="text/javascript"></script>
    <link href="/App_Themes/Default/jquery.dragToSelect.css" rel="stylesheet" type="text/css" />
    <link href="/App_Themes/Default/DrawForm.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/json.js" type="text/javascript"></script>
    <script type="text/javascript">
        var defaultoption=<%=GetControlDefaultAttribute() %>;  
        var CtrlDefaultOption = {};
        //递归获取控件属性
        function GetObject(object){
            if(object==null)
                return object;
            if(typeof object=="object"){
                var obj={};
                for(var i in object){
                    obj[i.toLowerCase()]=GetObject(object[i]);
                }
                return obj ;
            }
            else
                return object ;
        }
        //设置控件的默认属性
        function SetCtrlDefaultOption(){
            var obj=defaultoption;
            CtrlDefaultOption={};
            for(var i in obj){
                var o=obj[i];
                o=GetObject(o);
                if(o.caption===null)o.caption=i.toLowerCase();
                if(o.id==="")o.id="auto";
                o._type=o.type;
                delete o.type
                CtrlDefaultOption[i.toLowerCase()]=o;
            }        
        }
        var CtrlResizeOption={
            label:{handles:""},
            input:{handles:"w,e"}
        };
        var CtrlIdPools = [];
        //获取字符串的长度
        function GetStringLength(str) {
            return str.replace(/[^\x00-\xff]/g, "aa").length;
        }
        //获取控件的默认属性
        function GetCtrlDefaultOption(ctrlType) {
            var defaultOption = {
                id: "auto"
            };
            var option = CtrlDefaultOption[ctrlType];
            $.extend(defaultOption, option);
            if (!defaultOption.style)
                defaultOption.style = { height: 16, width: 0 };
            if (defaultOption.style.width <= 0) {
                var txtlen = 0;
                if (defaultOption.capiton && defaultOption.capiton != "")
                    txtlen = GetStringLength(defaultOption.capiton);
                if (txtlen > 0)
                    defaultOption.style.width = txtlen * 12;
            }
            if (defaultOption.id == "auto") {
                if (!CtrlIdPools[ctrlType])
                    CtrlIdPools[ctrlType] = 0;
                CtrlIdPools[ctrlType] = parseInt(CtrlIdPools[ctrlType]) + 1;
                defaultOption.id = ctrlType+ CtrlIdPools[ctrlType];                
            }
            if(!defaultOption["name"])
                defaultOption["name"]="";
            return defaultOption;
        }
        //根据枚举出来的数字获取控件类型
        function GetCtrlType(enumType){
            var type="";
            for(var i in defaultoption){
                var ctrl=defaultoption[i];
                if(ctrl["Type"]==enumType){
                    type=i;
                    break ;
                 }                
            }
            return type;
        }
        //根据JSON 增加控件
        function BuilderCtrl(json){
            if(!json || json=="")return ;
            json=eval("("+json +")");
            for(var i in json){
                var ctrl=json[i];
                var type=ctrl["type"];
                if(!isNaN(type))
                    type=GetCtrlType(type);
                AppendCtrlToContainer(type,ctrl.style,$("#canvas"),ctrl);
            }
        }
        //往容器里增加控件
        function AppendCtrlToContainer(ctrlType, offset, Container,options) {
            if (!offset.top)
                offset.top = 1;
            if (!offset.left)
                offset.left = 1;
            var defaultOption = GetCtrlDefaultOption(ctrlType);
            $.extend(defaultOption,options);
            if (!defaultOption.caption) {
                defaultOption.caption = "";
            }
            var html = [];
            html.push('<div class="design ' + ctrlType + ' easyui-draggable easyui-resizable">');
            var innerHtml = "<input class=' ";
            switch (ctrlType) {
                case "label":
                case "panel":
                    innerHtml = defaultOption.caption;
                    break;
                case "checkbox":
                case "radio":
                    innerHtml += ctrlType + "' type='" + ctrlType + "'/><label>" + defaultOption.caption + "</label>";
                    break;
                case "button":
                case "input":
                    html.pop();
                    innerHtml +="design "+ ctrlType + "' type='" + ctrlType + "' value='" + defaultOption.caption + "'/>";
                    break;
                case "combobox":
                    html.pop();
                    innerHtml += "design "+ ctrlType + "' type='value' value='下拉列表'/>";
                    break;
                case "jqgrid":
                    innerHtml ="<table class='easyui-datagrid'></table>";
                default:
                    break;
            }
            html.push(innerHtml);
            if (html.length > 1)
                html.push("</div>");
            var obj = $(html.join("")).css({
                top: offset.top,
                left: offset.left
            }).appendTo(Container);
            for(var i in defaultOption){
                if(i=="style" || i=="type")
                    continue ;
                if(typeof(defaultOption[i])=="object"){
                    obj.attr(i,defaultOption[i]);
                }
                if(defaultOption[i] && defaultOption[i]!="")
                    obj.attr(i,defaultOption[i]);
            }
            BindDesignCtrlEvent(obj);
        }
    </script>
    <script type="text/javascript">
        var curDropCtrl = null;
        //获取某个控件的控件类型
        function GetDesignCtrlType(selectedObj) {
            var reg = /design\s+|easyui-draggable\s?|easyui-resizable\s?|selected\s?/ig;
            var className = $(selectedObj).attr("class");
            var type = className.replace(reg, "").replace(/\s+/ig, "");
            return type;
        }
        //构造控件的属性.
        function BuilderProperty(selectedObj) {
            var type = GetDesignCtrlType(selectedObj);
            var ctrlProperty = GetCtrlDefaultOption(type);
            var data = [];
            var group, name, value, editor = "text";
            var getctrlattr = function (obj, attr) {
                var v = "";
                if (obj[attr])
                    v = obj[attr];
                else if (attr == "caption") {
                    if (obj.nodeName.toLowerCase() == "input")
                        v = $(obj).val();
                    else
                        v = $(obj).text();
                }
                else if (attr == "html")
                    v = $(obj).html();
                else if (attr == "enabled") {
                    v = !$(obj).attr("disabled")
                }
                else {
                    v = $(obj).attr(attr);
                }
                return v;
            }
            for (var i in ctrlProperty) {
                var property = ctrlProperty[i];
                if (i.indexOf("_") == 0)
                    continue;
                if (typeof (property) == "object") {
                    group = i;
                    var attrs = selectedObj[i];
                    if (!attrs)
                        attrs = $(selectedObj).attr(i);
                    if (attrs) {
                        for (var j in property) {
                            name = j;
                            value = attrs[name];
                            data.push({ name: name, value: value, group: group, editor: editor });
                        }
                    }
                }
                else {
                    group = "通常";
                    name = i;
                    value = getctrlattr(selectedObj, name);
                    if (typeof (value) == "boolean" || name == "enabled") {
                        if (!value) value = "false";
                        editor = {
                            type: 'combobox',
                            options: {
                                valueField: 'label',
                                textField: 'value',
                                data: [{
                                    label: 'true',
                                    value: 'true'
                                }, {
                                    label: 'false',
                                    value: 'false'
                                }]
                            }
                        };
                    }
                    data.push({ name: name, value: value, group: group, editor: editor });
                }
            }
            return data;
        }
        //更新某个控件的属性到表格上去.
        function UpdateProperty(ctrl) {
            var data = BuilderProperty(ctrl);
            $('#PropertyList').propertygrid("loadData", data);
        }
        //根据表格上的属性值更新控件
        function UpdateControl(ctrl, row) {
            if (row.group == "通常") {
                if (row["name"] == "caption") {
                    if (ctrl.nodeName.toLowerCase() == "input")
                        $(ctrl).val(row["value"]);
                    else
                        $(ctrl).text(row["value"]);
                }
                else if (row["name"] == "html")
                    $(ctrl).html(row["value"]);
                else if (row["name"] == "enabled") {
                    var v = row["value"];
                    if (v === "true" || v == true) {
                        $(ctrl).removeAttr("disabled");
                    }
                    else
                        $(ctrl).attr("disabled", "disabled");
                }
                else
                    $(ctrl).attr(row["name"], row["value"]);
            }
            else {
                if (!ctrl[row.group])
                    ctrl[row.group] = {};
                ctrl[row.group][row["name"]] = row["value"];
            }
        }
        //控件被选中
        function DesignCtrlSelected(selectedObj) {
            //更新前一个控件
            var rows = $('#PropertyList').propertygrid("getChanges", "updated");
            if (rows && rows.length > 0) {
                var ctrlId = "";
                for (var i in rows) {
                    if (rows[i]["name"] == "id") {
                        ctrlId = rows[i]["value"];
                        break;
                    }
                }
                if (ctrlId && ctrlId != "" && $("#" + ctrlId).size() > 0) {
                    var ctrl = $("#" + ctrlId)[0];
                    for (var i in rows) {
                        var row = rows[i];
                        UpdateControl(ctrl, row);
                    }
                }
            }
            //将当前控件的属性设置到属性列表中去
            UpdateProperty(selectedObj);
        }
        //绑定控件的事件
        function BindDesignCtrlEvent(objects) {
            var type = GetDesignCtrlType(objects); // $(objects).attr("class").replace(/design\s?|easyui-draggable\s?|\s?easyui-resizable\s?/ig, "");
            type = type.replace(/\s+/, "");
            var resizeoption = {
                handles: "n, e, s, w, ne, se, sw, nw, all",
                minWidth: 50, minHeight: 20
            };
            var ctrloption = CtrlResizeOption[type];
            resizeoption = $.extend(resizeoption, ctrloption);
            objects.bind("click", function (e) {
                if ($(this).hasClass("selected") && $(".selected").size() > 1) { }
                else {
                    $('#canvas .design').removeClass("selected");
                    $(this).addClass("selected");
                    DesignCtrlSelected(this);
                }
                return false;
            }).draggable({ edge: 5, onBeforeDrag: function (e) {
                $('#canvas').dragToSelect("disable");
                $(this).data("orioffset", { x: e.pageX, y: e.pageY });
                return true;
            }, onStopDrag: function (e) {
                $('#canvas').dragToSelect("enable");
                if ($(".selected").size() > 1) {
                    var objSelf = this;
                    var orioffset = $(this).data("orioffset");
                    var offx = e.pageX - orioffset.x;
                    var offy = e.pageY - orioffset.y;
                    $(".selected").not(objSelf).each(function (e, f) {
                        var top = parseInt(f.style.top);
                        var left = parseInt(f.style.left);
                        $(f).css({
                            top: top + offy + "px",
                            left: left + offx + "px"
                        });
                    });
                }
                return true;
            }
            }).resizable($.extend({
                onStopResize: function (e) {
                    UpdateProperty(this);
                }
            }, resizeoption));
        };

        $(function () {
            SetCtrlDefaultOption();
            $('#canvas').dragToSelect({
                selectables: '.design',
                onShow: function () {
                    return $("body").css("cursor").indexOf("-resize") < 0;
                },
                onHide: function () {
                    if ($(".selected").size() == 1) {
                        DesignCtrlSelected($(".selected")[0]);
                    }
                    return true;
                }
            }).bind("click", function (e) {
                if ($(".selected").size() < 1)//之所以绕这么大的圈的原因是选择完后,会把父元素的单击事件触发
                    DesignCtrlSelected(this);
                return false;
            });
            $('.ctrl').draggable({
                revert: true,
                proxy: function (source) {
                    var p = $("<div class='proxy'></div>");
                    p.append($(source).clone()).appendTo('body');
                    return p;
                },
                onStartDrag: function () {
                    $(this).draggable('options').cursor = 'not-allowed';
                },
                onStopDrag: function (e, f, g) {
                    $(this).draggable('options').cursor = 'move';
                    if (curDropCtrl && curDropCtrl != "") {
                        var reg = /ctrl\s+/ig;
                        curDropCtrl = curDropCtrl.replace(reg, "");
                        var canvasOffset = $("#canvas").offset();
                        var offset = {
                            left: e.clientX - (e.offsetX ? e.offsetX : 0) - canvasOffset.left,
                            top: e.clientY - (e.offsetY ? e.offsetY : 0) - canvasOffset.top
                        };
                        AppendCtrlToContainer(curDropCtrl, offset, $("#canvas"));
                    }
                }
            });
            $('#canvas').droppable({
                onDragEnter: function (e, source) {
                    $(source).draggable('options').cursor = 'auto';
                },
                onDragLeave: function (e, source) {
                    $(source).draggable('options').cursor = 'not-allowed';
                },
                onDrop: function (e, source) {
                    curDropCtrl = $(source).attr("class");
                }
            });
            $("#PropertyList").propertygrid({
                onAfterEdit: function (rowIndex, rowData, changes) {
                    if (changes && changes["value"] && changes["value"] != "") {
                        var ctrlId = "";
                        var rows = $("#PropertyList").propertygrid("getRows");
                        for (var i in rows) {
                            if (rows[i]["name"] == "id") {
                                ctrlId = rows[i]["value"];
                                break;
                            }
                        }
                        var ctrl = $("#" + ctrlId)[0];
                        UpdateControl(ctrl, rowData);
                    }
                }
            });

        });
    </script>
    <!--功能按钮区域-->
    <script type="text/javascript">
        $(function () {
            $(".align-icon").click(function () {
                var action = $(this).attr("class").replace(/align-icon\s+/, "");
                var offset_top = [], offset_left = [];
                $(".selected").each(function () {
                    var offset = $(this).offset();
                    offset_top.push(offset.top);
                    offset_left.push(offset.left);
                });
                var css = {};
                var canvasOffset = $("#canvas").offset();
                canvasOffset.left = canvasOffset.left + 2;
                switch (action) {
                    case "align-left":
                        css = { "left": Math.min.apply(Math, offset_left) - canvasOffset.left + "px" };
                        break;
                    case "align-right":
                        css = { "left": Math.max.apply(Math, offset_left) - canvasOffset.left + "px" };
                        break;
                    case "align-top":
                        css = { "top": Math.min.apply(Math, offset_top) - canvasOffset.top + "px" };
                        break;
                    case "align-bottom":
                        css = { "top": Math.max.apply(Math, offset_top) - canvasOffset.top + "px" };
                        break;
                }
                $(".selected").each(function () {
                    $(this).css(css);
                });
                return false;
            });
            function GetColumns(TableName, callback) {
                var url = "/tools/JSON.ashx?param=db&type=info&act=getcolumns&TableName=" + TableName;
                $.ajax({
                    url: url,
                    dataType: "json",
                    success: function (data) {
                        callback(data);
                    }
                });
            }
            $("#selformid").combobox({
                width: 200,
                url: 'DrawForm.ashx?act=getallformlist',
                valueField: '0',
                textField: '1',
                panelWidth: 200,
                panelHeight: 'auto',
                onChange: function (newValue, oldValue) {
                    if (!newValue || newValue == "")
                        return;
                    $.ajax({
                        url: "DrawForm.ashx?act=getformjson",
                        data: { formid: newValue },
                        success: function (data) {
                            var form = eval("(" + data + ")");
                            //debugger;
                            if (form && form.Layout.length > 0) {
                                BuilderCtrl(form.Layout[0].Jsondata);
                            }
                            else if (form) {
                                var TableName = form["Tablename"];
                                GetColumns(TableName, function (columns) {
                                    var offset = {
                                        left: 10,
                                        top: 10
                                    };
                                    for (var i in columns) {
                                        var col = columns[i];
                                        offset.top += 30;
                                        AppendCtrlToContainer("label", offset, $("#canvas"), { caption: col[1] });
                                        var inputOffset = new Object();
                                        inputOffset.left = offset.left + (4 * 12);
                                        inputOffset.top = offset.top;
                                        AppendCtrlToContainer("input", inputOffset, $("#canvas"), { name: col[0] });
                                    }
                                });
                            }
                        }
                    });
                }
            });
            $("#btnsave").click(function () {
                var ctrjson = [];
                var canvasOffset = $("#canvas").offset();
                var i = 0
                $("#canvas .design").each(function () {
                    var ctrl = $(this);
                    var type = GetDesignCtrlType(ctrl);
                    var ctrlProperty = null;
                    ctrlProperty = GetCtrlDefaultOption(type); //BuilderProperty(this);
                    ctrlProperty.type = ctrlProperty._type;
                    delete ctrlProperty._type;
                    for (var property in ctrlProperty) {
                        switch (property) {
                            case "type":
                                break;
                            case "value":
                                ctrlProperty[property] = ctrl.val();
                                break;
                            case "enabled":
                                ctrlProperty[property] = !ctrl.attr("disabled");
                                break;
                            case "caption":
                                if (type == "button")
                                    ctrlProperty[property] = ctrl.val();
                                else
                                    ctrlProperty[property] = ctrl.text();
                                break;
                            case "style":
                                var objstyle = new Object();
                                var offset = ctrl.offset();
                                objstyle["top"] = offset.top - canvasOffset.top;
                                objstyle["left"] = offset.left - canvasOffset.left;
                                objstyle["width"] = ctrl.width();
                                objstyle["height"] = ctrl.height();
                                ctrlProperty[property] = objstyle;
                                break;
                            default:
                                //debugger;
                                if (ctrl.attr(property)) {
                                    var p = ctrl.attr(property);
                                    if (p && p.indexOf("[object") > -1) {
                                        ctrlProperty[property] = ctrl[0][property];
                                    }
                                    else
                                        ctrlProperty[property] = ctrl.attr(property);
                                } break;
                        }
                    }
                    ctrjson.push(ctrlProperty);
                });
                var formid = $("#selformid").combobox("getValue");
                $.ajax({
                    url: "DrawForm.ashx?formid=" + formid,
                    type: "POST",
                    data: {
                        act: "savedesignform",
                        jsondata: JSON.stringify(ctrjson)
                    },
                    success: function (data) {
                        alert("保存成功");
                    }
                });
            });
            $("#btnProview").click(function () {
                var formid = $("#selformid").combobox("getValue");
                window.open("Parse.aspx?formid=" + formid);
                return false;
            });
            $("#btnDelete").click(function () {
                $(".selected").remove();
                return false;
            });
        });
    </script>
</head>
<body class="easyui-layout">
    <div data-options="region:'north'" style="height: 35px; padding-top: 3px; overflow:hidden ;">
        <button class="align-icon align-left">
        </button>
        <button class="align-icon align-right">
        </button>
        <button class="align-icon align-top">
        </button>
        <button class="align-icon align-bottom">
        </button>
        <select id="selformid">
            <option>请选择一个表单</option>
        </select>
        <button id="btnsave">
            保存
        </button>
        <button id="btnDelete">
            删除
        </button>
        <button id="btnProview">
            预览
        </button>
    </div>
    <div data-options="region:'east',split:true" title="属性" style="width: 200px;">
        <table id="PropertyList" class="easyui-propertygrid" data-options=" showGroup: true, showHeader: false, scrollbarSize: 0, fit: true">
        </table>
    </div>
    <div data-options="region:'west',split:true" title="控件列表" style="width: 150px;">
        <ul class="ctrllist">
            <li class="ctrl label"><span class="icon"></span><span class="text">标签</span></li>
            <li class="ctrl button"><span class="icon"></span><span class="text">按钮</span></li>
            <li class="ctrl panel"><span class="icon"></span><span class="text">面板</span></li>
            <li class="ctrl input"><span class="icon"></span><span class="text">输入框</span></li>
            <li class="ctrl checkbox"><span class="icon"></span><span class="text">复选框</span></li>
            <li class="ctrl radio"><span class="icon"></span><span class="text">单选框</span></li>
            <li class="ctrl combobox"><span class="icon"></span><span class="text">下拉框</span></li>
            <li class="ctrl jqgrid"><span class="icon"></span><span class="text">表格</span></li>
        </ul>
    </div>
    <div id="canvas" data-options="region:'center'">
    </div>
</body>
</html>
